﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.IO;
using Emgu.CV;
using Emgu.CV.Structure;
using ContourAnalysisNS;
using System.Runtime.Serialization.Formatters.Binary;

namespace CaptureWebcame
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            
            InitializeComponent();
            processor = new ImageProcessor();
            StartCapture();
            ApplyCamSettings();
            Application.Idle += new EventHandler(Application_Idle);
        }
        SqlConnection conn;
        private Capture _captureleft;
        private Capture _captureright;
        int camWidth = 640;
        int camHeight = 480;
        public bool captureFromCam = true;
        Image<Bgr, Byte> frameleft;
        Image<Bgr, Byte> frameright;
        ImageProcessor processor;
        int frameCount = 0;
        Dictionary<string, Image> AugmentedRealityImages = new Dictionary<string, Image>();        
        private SqlConnection connect()
        {
            conn = new SqlConnection(@"Data Source=nhphuoc-pc\sqlexpress;Initial Catalog=QuanLyGiuXe;Integrated Security=True");
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            else
            {
                conn.Close();
            }
            return conn;
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            txtMaThe.Focus();
            timer1.Interval = 1000;
            timer1.Enabled = true;
            timer1_Tick(sender, e);
        }               
        private void nhanxe()
        {
            SqlCommand cmd_insert = new SqlCommand("ADD_XE", connect());
            cmd_insert.CommandType = CommandType.StoredProcedure;
            cmd_insert.Parameters.Add(new SqlParameter("mathe", SqlDbType.VarChar)).Value = txtMaThe.Text;
            MemoryStream ms_trai = new MemoryStream();
            imgCapture.Image.Save(ms_trai, ImageFormat.Bmp);
            byte[] imageData_trai = ms_trai.GetBuffer();
            ms_trai.Dispose();
            ms_trai.Close();                        

            cmd_insert.Parameters.Add(new SqlParameter("HinhAnh", SqlDbType.Image)).Value = imageData_trai;
            cmd_insert.Parameters.Add(new SqlParameter("NgayNhan", SqlDbType.DateTime)).Value = DateTime.Now.ToString();
            lbNgayNhan.Text = DateTime.Now.ToString();
            lbNgayTra.Text = "";
            lbSoNgay.Text = "1";
            /*
            MemoryStream ms = new MemoryStream();
            imgCapturePhai.Image.Save(ms, ImageFormat.Bmp);
            byte[] imageData = ms.GetBuffer();
            ms.Dispose();
            ms.Close();                        
            cmd_insert.Parameters.Add(new SqlParameter("anhphai", SqlDbType.Image)).Value = imageData;
             * */
            cmd_insert.ExecuteNonQuery();
            connect().Dispose();
            connect().Close();
        }
        private void traxe()
        {
            try
            {
                SqlCommand cmd = new SqlCommand("LAY_XE", connect());
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("mathe", SqlDbType.NChar)).Value = txtMaThe.Text;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                /*
                byte[] imageData = new byte[0];
                imageData = (byte[])(dt.Rows[0]["AnhTrai"]);
                MemoryStream ms = new MemoryStream(imageData);
                imgCapture.SizeMode = PictureBoxSizeMode.StretchImage;
                imgCapture.Image = Image.FromStream(ms);
                ms.Dispose();
                ms.Close();
                 * */
                byte[] imageData_phai = new byte[0];
                imageData_phai = (byte[])(dt.Rows[0]["HinhAnh"]);
                MemoryStream ms_phai = new MemoryStream(imageData_phai);
                imgCapturePhai.SizeMode = PictureBoxSizeMode.StretchImage;
                imgCapturePhai.Image = Image.FromStream(ms_phai);
                ms_phai.Dispose();
                ms_phai.Close();
                
                lbNgayNhan.Text=dt.Rows[0]["NgayNhan"].ToString(); // hien thi lable ngay nhan
                lbNgayTra.Text = DateTime.Now.ToString(); // hien thi lable ngay tra                                                                                
                SqlCommand cmd_xoa = new SqlCommand("DELL_XE", connect());
                cmd_xoa.CommandType = CommandType.StoredProcedure;
                cmd_xoa.Parameters.Add(new SqlParameter("mathe", SqlDbType.NChar)).Value = txtMaThe.Text;                
                cmd_xoa.ExecuteNonQuery();
                connect().Dispose();
                connect().Close();
                txtMaThe.Clear();
                txtMaThe.Focus();
            }
            catch
            {
                MessageBox.Show("Error","Thông Báo",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }
        private void txtMaThe_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                
                
                SqlCommand cmd = new SqlCommand("LAY_XE", connect());
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("mathe", SqlDbType.VarChar)).Value = txtMaThe.Text;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count <= 0)
                {
                    imgCapture.Image = _captureleft.QueryFrame().ToBitmap();
                    imgCapture.SizeMode = PictureBoxSizeMode.StretchImage;
                    imgCapturePhai.ImageLocation = @"bg.png";
                    nhanxe();
                    txtMaThe.Clear();
                    txtMaThe.Focus();
                }
                else
                {
                    imgCapturePhai.SizeMode = PictureBoxSizeMode.StretchImage;
                    imgCapture.ImageLocation = @"bg.png";
                    traxe();                    
                    txtMaThe.Clear();
                    txtMaThe.Focus();
                }
            }          
        }
        private void StartCapture()
        {
            try
            {
                _captureleft = new Capture(0);
                _captureright = new Capture(2);
                ApplyCamSettings();
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }        
        private void ApplyCamSettings()
        {
            try
            {
                _captureleft.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, camWidth);
                _captureleft.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, camHeight);
                _captureright.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, camWidth);
                _captureright.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, camHeight);
                //cbCamResolution.Text = camWidth + "x" + camHeight;
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void Application_Idle(object sender, EventArgs e)
        {
            ProcessFrame();
        }
        private void ProcessFrame()
        {
            try
            {
                if (captureFromCam)
                {
                    frameleft = _captureleft.QueryFrame();
                    frameright = _captureright.QueryFrame();
                }
                else
                {
                    frameCount++;
                }
                //                 
                processor.ProcessImage(frameleft);
                processor.ProcessImage(frameright);
                //            
                imgVideo.Image = frameleft;
                imgVideoPhai.Image = frameright;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }        
        private void button1_Click(object sender, EventArgs e)
        {
            imgCapture.Image = _captureleft.QueryFrame().ToBitmap();
            imgCapturePhai.Image = _captureright.QueryFrame().ToBitmap();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lbThoiGian.Text = DateTime.Now.ToString();
        }
    }
}
